package com.xwj.controller;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author xwj
 * @date 2020/5/9
 */
@Component
public class OrderListener {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(queues = "order-consumer-queue")
    public void consumerDelayOrder1(String orderId, Message message, Channel channel) throws IOException {
        System.out.println("============消费订单延时队列1==============");
        System.out.println("消费时间：" + LocalDateTime.now());
        System.out.println("交换机：" + message.getMessageProperties().getReceivedExchange());
        System.out.println("routing key：" + message.getMessageProperties().getReceivedRoutingKey());
        System.out.println("队列：" + message.getMessageProperties().getConsumerQueue());
        System.out.println("取消订单：" + orderId);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 避免消息重复消费
        boolean result = stringRedisTemplate.opsForValue().setIfAbsent("order-consumer-queue-" + orderId, "order-consumer-queue-" + orderId);
        if (result) {
            // 第二个参数表示是否批量处理
            channel.basicAck(deliveryTag, true);
        } else {
            System.out.println("重复消费，丢弃消息");
            // 第二个参数是否requeue，true则重新入队列，否则丢弃或者进入死信队列
            channel.basicReject(deliveryTag, false);
        }
        System.out.println("=======================================");
    }

    @RabbitListener(queues = "order-consumer-queue")
    public void consumerDelayOrder2(String orderId, Message message, Channel channel) throws IOException {
        System.out.println("============消费订单延时队列2==============");
        System.out.println("消费时间：" + LocalDateTime.now());
        System.out.println("交换机：" + message.getMessageProperties().getReceivedExchange());
        System.out.println("routing key：" + message.getMessageProperties().getReceivedRoutingKey());
        System.out.println("队列：" + message.getMessageProperties().getConsumerQueue());
        System.out.println("取消订单：" + orderId);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 使用redis避免重复消费
        boolean result = stringRedisTemplate.opsForValue().setIfAbsent("order-consumer-queue-" + orderId, "order-consumer-queue-" + orderId);
        if(result) {
            // 第二个参数表示是否批量处理
            channel.basicAck(deliveryTag, true);
        } else {
            System.out.println("重复消费，丢弃消息");
            // 第二个参数是否requeue，true则重新入队列，否则丢弃或者进入死信队列
            channel.basicReject(deliveryTag, false);
        }
        System.out.println("=======================================");
    }
}
